package com.practice.utils;

import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

public class ExceptionHandler implements HandlerExceptionResolver {
	
	private static final Logger logger = Logger.getLogger(ExceptionHandler.class);
	
	@Override
	public ModelAndView resolveException(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex) {
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		logger.error(dateFormat.format(new Date()) + "异常信息：",ex);

		ModelAndView mv = new ModelAndView("../../error");
		String errorName = "";
		
		if(ex instanceof NullPointerException){
			errorName = "空指针";
		}else if(ex instanceof NumberFormatException){
			errorName = "数字类型转换失败";
		}else if(ex instanceof SocketTimeoutException || ex instanceof ConnectException){
			errorName = "网络异常";
		}else{
			errorName = "未知错误";
		}
		mv.addObject("errorName", errorName);
		mv.addObject("errorSource", request.getContextPath() + request.getServletPath());
		mv.addObject("errorInfo", ex);
		return mv;
	}

}
